import {
  Toast,
  MessageBox
} from "mint-ui";
import CryptoJS from "crypto-js";
var u = navigator.userAgent.toLowerCase();
export default {
  // 获取url的主机地址 如： http://localhost:8083 
  getLocalhostPath() {
    let localhostPath;
    let curWwwPath = window.document.location.href;
    //获取主机地址之后的目录，如： uimcardprj/share/meun.jsp
    let pathName = window.document.location.pathname;
    if (pathName == "/") { //即根目录
      localhostPath = curWwwPath;
    } else {
      let pos = curWwwPath.indexOf(pathName);
      //获取主机地址，如： http://localhost:8083
      localhostPath = curWwwPath.substring(0, pos);
    }

    return localhostPath;
  },
  getDate: function (AddDayCount) {
    //获取日期，如当天传0,昨天传-1
    var dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1; //获取当前月份的日期
    var d = dd.getDate();
    return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d);
  },
  // 只有年月日
  formatDate(secs) {
    var t = new Date(secs);
    var year = t.getFullYear();
    var month = t.getMonth() + 1;
    if (month < 10) {
      month = "0" + month;
    }
    var date = t.getDate();
    if (date < 10) {
      date = "0" + date;
    }
    var hour = t.getHours();
    if (hour < 10) {
      hour = "0" + hour;
    }
    var minute = t.getMinutes();
    if (minute < 10) {
      minute = "0" + minute;
    }
    var second = t.getSeconds();
    if (second < 10) {
      second = "0" + second;
    }
    return year + "-" + month + "-" + date;
  },
  // 年月日时分
  formatDateMin(secs) {
    var t = new Date(secs);
    var year = t.getFullYear();
    var month = t.getMonth() + 1;
    if (month < 10) {
      month = "0" + month;
    }
    var date = t.getDate();
    if (date < 10) {
      date = "0" + date;
    }
    var hour = t.getHours();
    if (hour < 10) {
      hour = "0" + hour;
    }
    var minute = t.getMinutes();
    if (minute < 10) {
      minute = "0" + minute;
    }
    var second = t.getSeconds();
    if (second < 10) {
      second = "0" + second;
    }
    return (
      year + "-" + month + "-" + date + " " + hour + ":" + minute + ":" + second
    );
  },
  // 计算星期
  // date ("2019-01-01")
  getWeek: function (date) {
    let weekArray = new Array(
      "周日",
      "周一",
      "周二",
      "周三",
      "周四",
      "周五",
      "周六"
    );
    return weekArray[new Date(date).getDay()];
  },
  hideInfo: function (str, frontLen, endLen) {
    // 隐藏指定字符串
    var len = str.length - frontLen - endLen;
    var xing = "";
    for (var i = 0; i < len; i++) {
      xing += "*";
    }
    return (
      str.substring(0, frontLen) + xing + str.substring(str.length - endLen)
    );
  },
  hideindex: function (str, index) {
    // 隐藏指定下表位置的字符串
    var xing = "*";
    if (str.length > 2) {
      return str.substring(0, index) + xing + str.substring(str.length - index);
    } else {
      return str.substring(0, index) + xing;
    }
  },
  cutStr(str, L) {
    //截取字符串
    var result = "",
      strlen = str.length, // 字符串长度
      chrlen = str.replace(/[^\x00-\xff]/g, "**").length; // 字节长度

    if (chrlen <= L) {
      return str;
    }

    for (var i = 0, j = 0; i < strlen; i++) {
      var chr = str.charAt(i);
      if (/[\x00-\xff]/.test(chr)) {
        j++; // ascii码为0-255，一个字符就是一个字节的长度
      } else {
        j += 2; // ascii码为0-255以外，一个字符就是两个字节的长度
      }
      if (j <= L) {
        // 当加上当前字符以后，如果总字节长度小于等于L，则将当前字符真实的+在result后
        result += chr;
      } else {
        // 反之则说明result已经是不拆分字符的情况下最接近L的值了，直接返回
        return result;
      }
    }
  },
  isPhone: function (pone) {
    // 判断是否是手机号码
    var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
    if (!myreg.test(pone)) {
      return false;
    } else {
      return true;
    }
  },
  idcardGetinfo(UUserCard, num) {
    // 根据身份证号获取信息
    if (num == 1) {
      //获取出生日期
      var birth =
        UUserCard.substring(6, 10) +
        "-" +
        UUserCard.substring(10, 12) +
        "-" +
        UUserCard.substring(12, 14);
      return birth;
    }
    if (num == 22) {
      //获取性别
      if (parseInt(UUserCard.substr(16, 1)) % 2 == 1) {
        return "男"; //男
      } else {
        return "女"; //女
      }
    }
    if (num == 2) {
      //获取性别
      if (parseInt(UUserCard.substr(16, 1)) % 2 == 1) {
        return "1"; //男
      } else {
        return "2"; //女
      }
    }
    if (num == 3) {
      //获取年龄
      var myDate = new Date();
      var month = myDate.getMonth() + 1;
      var day = myDate.getDate();
      var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
      if (
        UUserCard.substring(10, 12) < month ||
        (UUserCard.substring(10, 12) == month &&
          UUserCard.substring(12, 14) <= day)
      ) {
        age++;
      }
      return age;
    }
  },

  isIDcard: function (idcode) {
    // 判断是否是身份证号
    // 函数参数必须是字符串，因为二代身份证号码是十八位，而在javascript中，十八位的数值会超出计算范围，造成不精确的结果，导致最后两位和计算的值不一致，从而该函数出现错误。
    // 加权因子
    var weight_factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    // 校验码
    var check_code = ["1", "0", "X", "9", "8", "7", "6", "5", "4", "3", "2"];
    var code = idcode + "";
    var last = idcode[17]; //最后一位
    var seventeen = code.substring(0, 17);
    // ISO 7064:1983.MOD 11-2
    // 判断最后一位校验码是否正确
    var arr = seventeen.split("");
    var len = arr.length;
    var num = 0;
    for (var i = 0; i < len; i++) {
      num = num + arr[i] * weight_factor[i];
    }
    // 获取余数
    var resisue = num % 11;
    var last_no = check_code[resisue];
    // 格式的正则
    // 正则思路
    /*
    第一位不可能是0
    第二位到第六位可以是0-9
    第七位到第十位是年份，所以七八位为19或者20
    十一位和十二位是月份，这两位是01-12之间的数值
    十三位和十四位是日期，是从01-31之间的数值
    十五，十六，十七都是数字0-9
    十八位可能是数字0-9，也可能是X
    */
    var idcard_patter = /^[1-9][0-9]{5}([1][9][0-9]{2}|[2][0][0|1][0-9])([0][1-9]|[1][0|1|2])([0][1-9]|[1|2][0-9]|[3][0|1])[0-9]{3}([0-9]|[X])$/;
    // 判断格式是否正确
    var format = idcard_patter.test(idcode);
    // 返回验证结果，校验码和格式同时正确才算是合法的身份证号码
    return last === last_no && format ? true : false;
  },
  toast(data) {
    Toast({
      message: data,
      position: "center",
      duration: 1500
    });
  },
  MessageBox(obj) {
    MessageBox.confirm(obj.message)
      .then(action => {
        obj.confirm(action);
      })
      .catch(cancel => {
        obj.cancel(cancel);
      });
  },
  alert(obj) {
    MessageBox.alert(obj.message).then(action => {
      obj.alert(action);
    });
  },
  //获取URL参数
  getRequest: function (key) {
    var url = decodeURI(location.search); //获取url中"?"符后的字串
    var theRequest = new Object();
    if (url.indexOf("?") != -1) {
      var str = url.substring(url.indexOf("?") + 1, url.length);
      var strs = str.split("&");
      for (var i = 0; i < strs.length; i++) {
        if (strs[i])
          theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
      }
    }
    if (!key) return theRequest;
    else return theRequest[key];
  },
  // 获取url参数值
  GetUrlParams() {
    let arr,
      name,
      value,
      str = location.href,
      num = str.indexOf("?"); //取得整个地址栏
    str = str.substr(num + 1); //取得所有参数 stringvar.substr(start [, length ]
    if (str.indexOf("#/") > -1) {
      arr = str.split("#/")[0].split("&");
    } else {
      arr = str.split("&"); //各个参数放到数组里
    }

    for (let i = 0; i < arr.length; i++) {
      num = arr[i].indexOf("=");
      if (num > 0) {
        name = arr[i].substring(0, num);
        value = arr[i].substr(num + 1);
        this[name] = value;
      }
    }
  },
  // 判断是当前值否为对象{}
  isPlainObject: function (o) {
    if (o instanceof Array) {
      return "Array";
    } else if (o instanceof Object) {
      return "Object";
    } else {
      return false;
    }
  },
  //加密身份证号码
  encrypt: function (content) {
    var sKey = CryptoJS.enc.Utf8.parse("wonderscdjkdyapp");
    var sContent = CryptoJS.enc.Utf8.parse(content);
    var encrypted = CryptoJS.AES.encrypt(sContent, sKey, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });
    return encrypted.ciphertext.toString().toUpperCase();
  },

  //解密身份证号码
  decrypt: function (content) {
    var encryptedHexStr = CryptoJS.enc.Hex.parse(content);
    var sKey = CryptoJS.enc.Utf8.parse("wonderscdjkdyapp");
    var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
    var decrypt = CryptoJS.AES.decrypt(srcs, sKey, {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7
    });
    var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
  },
  // 金额 分转元
  moneyChange: function (fen) {
    if (!fen) {
      return 0;
    }
    let num = fen * 0.01;
    num += "";
    let reg =
      num.indexOf(".") > -1 ?
      /(\d{1,3})(?=(?:\d{3})+\.)/g :
      /(\d{1,3})(?=(?:\d{3})+$)/g;
    num = num.replace(reg, "$1");
    num = this.toDecimal2(num);
    return num;
  },
  // 强制有2位小数
  toDecimal2: function (x) {
    let f = parseFloat(x);
    if (isNaN(f)) {
      return false;
    }
    f = Math.round(x * 100) / 100;
    let s = f.toString();
    let rs = s.indexOf(".");
    if (rs < 0) {
      rs = s.length;
      s += ".";
    }
    while (s.length <= rs + 2) {
      s += "0";
    }
    return s;
  },
  // 计算2个日期间的天数
  DateDiff: function (sDate, eDate) {
    //sDate和eDate是yyyy-MM-dd格式
    let date1 = new Date(sDate);
    let date2 = new Date(eDate);
    let date3 = date2.getTime() - date1.getTime();
    let days = Math.floor(date3 / (24 * 3600 * 1000));
    days = days ? days : "";
    return days;
  },
  isWeiXin: function () {
    let ua = window.navigator.userAgent.toLowerCase();
    if (ua.match(/MicroMessenger/i) == "micromessenger") {
      return true; // 是微信端
    } else {
      return false;
    }
  },
  isIos: function () {
    let u = navigator.userAgent;
    if (!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
      return true;
    } else {
      return false;
    }
  },
  isAndroid: function () {
    let u = navigator.userAgent;
    if (u.indexOf("Android") > -1 || u.indexOf("Adr") > -1) {
      return true;
    } else {
      return false;
    }
  },
  /**
   * 浏览器判断
   */
  QuickVersion: {
    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
    android: u.indexOf("android") > -1 || u.indexOf("Linux") > -1, // android终端或uc浏览器
    iPhone: u.indexOf("iphone") != -1, // 是否为iPhone或者QQHD浏览器
    iPad: u.indexOf("ipad") > -1, // 是否iPad
    isWeb: u.indexOf("windows nt") != -1 ||
      (u.indexOf("mac os") != -1 && u.indexOf("ios_appname") == -1), //是否PC浏览器 不完善！！！
    isWeixin: u.indexOf("micromessenger") != -1, //是否微信
    isApp: u.indexOf("android_appname") != -1, //是否手机APP  apache-httpclient/unavailable (java 1.4) android_appName
    isIOSApp: u.indexOf("ios_appname") != -1,
    isIE: function () {
      if (!!window.ActiveXObject || "ActiveXObject" in window) return true;
      else return false;
    },
    isMobileApp: function (key) {
      return u.indexOf(key) != -1;
    }
  },

};